import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store/store";
import ElementUI from "element-ui";

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404.vue')
  },
  {
    path: '/front',
    name: 'Front',
    component: () => import('../views/front/Front.vue'),
    children: [
      { path: 'home', name: 'FrontHome', component: () => import('../views/front/Home.vue') },
      { path: 'page1', name: 'Page1', component: () => import('../views/front/Page1.vue') },
    ]
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//提供一个重置路由的方法
export const resetRouter = () => {
  router.matcher = new VueRouter( {
    mode: 'history',
    base: process.env.BASE_URL,
    routes
  })
}

//实现动态路由（根据用户的角色拥有的菜单来分配路由）
//注：刷新页面会重置路由
export const setRoutes = () => {
  const storeMenus = localStorage.getItem("menus");
  if (storeMenus) {
    //获取当前的路由对象名称数组
    const currentRouteNames = router.getRoutes().map(v => v.name);
    if (!currentRouteNames.includes('Manage')){
      //拼装动态路由
      const manageRoute = { path: '/', name: 'Manage', component: () => import('../views/Manage.vue'), redirect: "/home", children: [
          //每个人都可以修改个人信息和密码，所以这两个路由是固定的
          { path: 'person', name: '个人信息', component: () => import('../views/Person.vue')},
          { path: 'password', name: '修改密码', component: () => import('../views/Password.vue')},
        ] };
      const menus = JSON.parse(storeMenus);
      menus.forEach(item => {
        if (item.path) {  //当且仅当path不为空的时候才去设置路由
          let itemMenu = {
            path: item.path.replace("/", ""),
            name: item.name,
            component: () => import('../views/' + item.pagePath + '.vue')
          };
          manageRoute.children.push(itemMenu);
        } else if (item.children.length){
          item.children.forEach(item => {
            if (item.path) {  //当且仅当path不为空的时候才去设置路由
              let itemMenu = {
                path: item.path.replace("/", ""),
                name: item.name,
                component: () => import('../views/' + item.pagePath + '.vue')
              };
              manageRoute.children.push(itemMenu);
            }
          })
        }
      })
      //动态添加到现在的路由对象中去
      router.addRoute(manageRoute);
    }
  }
}

//如果路由被重置，则刷新一次路由
setRoutes();

// 路由守卫
router.beforeEach((to, from, next) => {
  localStorage.setItem("currentPathName", to.name);  // 设置当前的路由名称，为了在Header组件中去使用
  store.commit("setPath");  // 触发store的数据更新

  const storeMenus = localStorage.getItem("menus");
  if (!to.matched.length) {  //未找到路由的情况
    if (storeMenus) {      //如果有storeMenus（表示已登录）
      next("/404");    //跳转到404
    } else {               //如果没登录
      ElementUI.Message({
        message: '请先登录！',
        type: 'error'
      });
      next("/login");  //跳转到登陆界面
    }
  }
  next();   //如果找到路由，则正常放行
})

export default router
